package com.gxa.p2p.controller;

import com.alibaba.excel.EasyExcel;
import com.gxa.p2p.common.JsonResult;
import com.gxa.p2p.pojo.Expmarklog;
import com.gxa.p2p.pojo.Investrecord;
import com.gxa.p2p.pojo.Outrecord;
import com.gxa.p2p.pojo.Rechargerecord;
import com.gxa.p2p.service.RechargerecordService;
import com.gxa.p2p.util.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.hssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/rechargerecord")
@WebAppConfiguration
//@Transactional
@Api(value = "交易接口")
public class RechargerecordController extends HttpServlet {
    @Autowired
    private RechargerecordService rechargerecordService=null;
    /**
     * 罗雪锋
     * @param id
     * @param investPhone
     * @param rechargeType
     * @param from
     * @param to
     * @param page
     * @param size
     * @return
     */
    @PostMapping("/findRechargelogByPage")
    @ApiOperation("查看充值记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "充值单号",required = false),
            @ApiImplicitParam(name = "investPhone",value = "用户电话",required = false),
            @ApiImplicitParam(name = "rechargeType",value = "充值方式",required = false),
            @ApiImplicitParam(name = "from",value = "开始时间",required = false),
            @ApiImplicitParam(name = "to",value = "截至时间",required = false),
            @ApiImplicitParam(name = "page",value = "页数",required = true),
            @ApiImplicitParam(name = "size",value = "每页数据",required = true),
            @ApiImplicitParam(name = "state",value = "充值状态",required = false)
    })
    public Map findRechargelogByPage(Long id,  String investPhone,
                                     String rechargeType,String state, String from,
                                     String to, @RequestParam("page") Integer page,
                                     @RequestParam("size") Integer size){
        Timestamp from1=null;
        Timestamp to1=null;
        if(from!=null&&!from.equals("")){
            from1=Timestamp.valueOf(from);
        }
        if(to!=null&&!to.equals("")){
            to1=Timestamp.valueOf(to);
        }
        Boolean state1=null;
        if(state!=null&&!state.equals("")){
            state1 = Boolean.valueOf(state);
        }
        System.out.println("from"+from);
        System.out.println("to"+to);
        List<Rechargerecord> mapList = rechargerecordService.findRechargelogByPage(id, investPhone, rechargeType, state1, from1, to1, page, size);
        //System.out.println("11111111111111111111111");
        List<Rechargerecord> rechargerecords = rechargerecordService.selectByWork(id, investPhone, rechargeType, state1, from1, to1);
        int size1 = rechargerecords.size();
        JsonResult jsonResult=new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setData(mapList);
        jsonResult.put("count",size1);
        return jsonResult.getDataMap();
    }

    /**
     * 罗雪锋
     * @return
     */
    /*@GetMapping("/rechargelog")
    @ApiOperation(value = "导出充值记录")*/
    /*@ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "充值单号",required = false,paramType = "query"),
            @ApiImplicitParam(name = "investPhone",value = "用户电话",required = false,paramType = "query"),
            @ApiImplicitParam(name = "rechargeType",value = "充值方式",required = false,paramType = "query"),
            @ApiImplicitParam(name = "from",value = "开始时间",required = false,paramType = "query"),
            @ApiImplicitParam(name = "to",value = "截至时间",required = false,paramType = "query"),
            @ApiImplicitParam(name = "page",value = "页数",required = false,paramType = "query"),
            @ApiImplicitParam(name = "size",value = "每页数据",required = false,paramType = "query"),
            @ApiImplicitParam(name = "state",value = "充值状态",required = false,paramType = "query")
    })*/
    /*@ApiImplicitParams({
            @ApiImplicitParam(name = "deleteIds[]", value = "待导出内容的id的数组", required = true, dataType = "List")
    })*/
    /*public ResponseEntity<byte[]> rechargelog(Long id,  String investPhone,
                                                  String rechargeType, Boolean state, Timestamp from,
                                                 Timestamp to, Integer page,
                                                  Integer size,
                                                  *//*@RequestParam("fileName")String fileName,*//*
                                              HttpServletResponse response) throws IOException {
        // 查询到需要导出的集合
        //List<Map> maps = rechargerecordService.findRechargelogByPage(id, investPhone, rechargeType, state, from, to, page, size);
        List<Rechargerecord> maps = rechargerecordService.selectByWork(id, investPhone, rechargeType, state, from, to);
        System.out.println(maps);*/
        /*response.setContentType("applicationnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        fileName= URLEncoder.encode("充值记录表","utf-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), Rechargerecord.class).sheet("模板").doWrite(maps);*/
        /*//返回给前端下载
        response.setContentType("application/octet-stream");
        // 告诉浏览器，以附件方式打开，而不是在页面上浏览
        response.setHeader("Content-disposition", "attachment;filename=" + fileName +".xls");
        response.flushBuffer();
        EasyExcel.write(response.getOutputStream(),OrderVo.class).sheet("导出示例").doWrite(lists);
        // 生成json的结果集传给前端
        JsonResult jsonResult = new JsonResult();
        // 给json结果集赋值
        jsonResult.setCode("1");
        jsonResult.setMsg("查询成功");
        // 通过return返回给前端
        return jsonResult.getDataMap();*/
        // 创建字节数组缓冲流
        /*ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        // 语雀的核心写操作
        EasyExcel.write(outputStream, Rechargerecord.class).sheet("充值记录表表").doWrite(maps);
        // 缓冲数组
        byte[] bytes = outputStream.toByteArray();

        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentDispositionFormData("attachment", URLEncoder.encode("充值记录表.xlsx", "utf-8"));

        return new ResponseEntity<>(bytes, httpHeaders, HttpStatus.OK);
    }*/
    @GetMapping("/rechargelog")
    @ApiOperation("导出充值记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "充值单号",required = false,paramType = "query"),
            @ApiImplicitParam(name = "investPhone",value = "用户电话",required = false,paramType = "query"),
            @ApiImplicitParam(name = "rechargeType",value = "充值方式",required = false,paramType = "query"),
            @ApiImplicitParam(name = "from",value = "开始时间",required = false,paramType = "query"),
            @ApiImplicitParam(name = "to",value = "截至时间",required = false,paramType = "query"),
            @ApiImplicitParam(name = "state",value = "充值状态",required = false,paramType = "query")
    })
    public void rechargelog(Long id,  String investPhone,
                            String rechargeType, String state, String from,
                            String to,HttpServletResponse response) throws Exception {
        Timestamp from1=null;
        Timestamp to1=null;
        if(from!=null&&!from.equals("")){
            from1=Timestamp.valueOf(from);
        }
        if(to!=null&&!to.equals("")){
            to1=Timestamp.valueOf(to);
        }
        Boolean state1=null;
        if(state!=null&&!state.equals("")){
           state1= Boolean.valueOf(state);
        }
        //要导出的数据
        List<Rechargerecord> expMarkLogByPage = rechargerecordService.selectByWork(id, investPhone, rechargeType, state1, from1, to1);
        System.out.println(expMarkLogByPage);
        // 工作簿对象
        HSSFWorkbook workbook = new HSSFWorkbook();
        // 创建工作表
        HSSFSheet sheet = workbook.createSheet("体验金记录");
        String fileName = "充值记录导出记录"+".xls";
        // 将文件名中的中文部分被URL编码后的内容进行解析, 最终还是显示为中文状态
        fileName = URLEncoder.encode(fileName,"utf-8").replaceAll("\\+", "%20");
        // headers表示excel表中第一行的表头 在excel表中添加表头
        String[] headers = { "充值记录单号", "投资人电话", "投资人姓名","投资人来源","应用来源","充值金额","到账金额","手续费","充值方式","交易流水号","订单时间","到账时间","充值状态","充值记录备注","资金类型"};
        // 创建一个行对象, 作为表头
        HSSFRow row = sheet.createRow(0);
        for(int i=0;i<headers.length;i++){
            HSSFCell cell = row.createCell(i);   // 在行中添加单元格
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            cell.setCellValue(text);   // 把字段名添加到表头行上
        }
        //准备将时间格式处理为标准日期格式
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 添加数据行:
        int rowNum = 1;
        for (Rechargerecord item : expMarkLogByPage) {
            HSSFRow dataRow = sheet.createRow(rowNum);
            if (item.getId() == null) {
                dataRow.createCell(0).setCellValue("");
            } else {
                dataRow.createCell(0).setCellValue(item.getId());
            }
            if (item.getInvestPhone() == null) {
                dataRow.createCell(1).setCellValue("");
            } else {
                dataRow.createCell(1).setCellValue(item.getInvestPhone());
            }
            if (item.getInverstName() == null) {
                dataRow.createCell(2).setCellValue("");
            } else {
                dataRow.createCell(2).setCellValue(item.getInverstName());
            }
            if (item.getInvestOrigin() == null) {
                dataRow.createCell(3).setCellValue("");
            } else {
                dataRow.createCell(3).setCellValue(item.getInvestOrigin());
            }
            if (item.getInvestOrigin() == null) {
                dataRow.createCell(4).setCellValue("");
            } else {
                dataRow.createCell(4).setCellValue(item.getApplicationOrigin());
            }
            if (item.getRecharageMoney() == null) {
                dataRow.createCell(5).setCellValue("");
            } else {
                dataRow.createCell(5).setCellValue(item.getRecharageMoney());
            }
            if (item.getRecievedTime() == null) {
                dataRow.createCell(6).setCellValue("");
            } else {
                dataRow.createCell(6).setCellValue(item.getRecievedTime());
            }
            if (item.getServiceMoney() == null) {
                dataRow.createCell(7).setCellValue("");
            } else {
                dataRow.createCell(7).setCellValue(item.getServiceMoney());
            }
            if (item.getRechargeType() == null) {
                dataRow.createCell(8).setCellValue("");
            } else {
                dataRow.createCell(8).setCellValue(item.getRechargeType());
            }
            if (item.getSerialNumber() == null) {
                dataRow.createCell(9).setCellValue("");
            } else {
                dataRow.createCell(9).setCellValue(item.getSerialNumber());
            }
            if (item.getOrderTime() == null) {
                dataRow.createCell(10).setCellValue("");
            } else {
                dataRow.createCell(10).setCellValue(dateFormat.format(item.getOrderTime()));
            }
            if (item.getRecievedTime() == null) {
                dataRow.createCell(11).setCellValue("");
            } else {
                dataRow.createCell(11).setCellValue(dateFormat.format(item.getRecievedTime()));
            }
            if (item.getState() == null) {
                dataRow.createCell(12).setCellValue("");
            } else {
                dataRow.createCell(12).setCellValue(item.getState());
            }
            if (item.getRemarks() == null) {
                dataRow.createCell(13).setCellValue("");
            } else {
                dataRow.createCell(13).setCellValue(item.getRemarks());
            }
            if (item.getMoneyType() == null) {
                dataRow.createCell(14).setCellValue("");
            } else {
                dataRow.createCell(14).setCellValue(item.getMoneyType());
            }
            rowNum++;
        }
        //返回给前端下载
        response.setContentType("application/octet-stream");
        //附件格式打卡，不是打开页面
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        response.flushBuffer();
        workbook.write(response.getOutputStream());
    }
    /**
     * 罗雪锋
     * @param id
     * @param
     * @param
     * @param userName
     * @param from
     * @param to
     * @param page
     * @param size
     * @param bankId
     * @param bankName
     * @param state
     * @return
     */
    @PostMapping("/findWithdrawlogByPage")
    @ApiOperation("查看提现记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "提现单号",required = false),
            @ApiImplicitParam(name = "userPhone",value = "用户电话号",required = false),

            @ApiImplicitParam(name = "userName",value = "用户真实姓名",required = false),
            @ApiImplicitParam(name = "from",value = "开始时间",required = false),
            @ApiImplicitParam(name = "to",value = "截至时间",required = false),
            @ApiImplicitParam(name = "page",value = "页数",required = true),
            @ApiImplicitParam(name = "size",value = "每页数据",required = true),
            @ApiImplicitParam(name = "bankId",value = "银行账号",required = false),
            @ApiImplicitParam(name = "bankName",value = "银行名称",required = false),
            @ApiImplicitParam(name = "state",value = "提现状态",required = false)
    })
    public Map findWithdrawlogByPage(Long id, String userPhone,
                                      String userName,
                                      String bankId, String bankName,
                                      String state,String from, String to,
                                     @RequestParam("page") Integer page,@RequestParam("size") Integer size
    ){
        Timestamp from1=null;
        Timestamp to1=null;
        if(from!=null&&!from.equals("")){
            from1=Timestamp.valueOf(from);
        }
        if(to!=null&&!to.equals("")){
            to1=Timestamp.valueOf(to);
        }
        List<Outrecord> mapList = rechargerecordService.findWithdrawlogByPage(id, userPhone, userName, bankId, bankName, state, from1, to1, page, size);
        List<Outrecord> outrecords = rechargerecordService.selectByWork1(id, userPhone, userName, bankId, bankName, state, from1, to1);
        int size1 = outrecords.size();
        JsonResult jsonResult=new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setData(mapList);
        jsonResult.put("count",size1);
        return jsonResult.getDataMap();
    }
    @GetMapping("/withdrawlog")
    @ApiOperation("提现记录导出")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "提现单号",required = false),
            @ApiImplicitParam(name = "userPhone",value = "用户电话号",required = false),
            @ApiImplicitParam(name = "userName",value = "用户真实姓名",required = false),
            @ApiImplicitParam(name = "from",value = "开始时间",required = false),
            @ApiImplicitParam(name = "to",value = "截至时间",required = false),
            @ApiImplicitParam(name = "bankId",value = "银行账号",required = false),
            @ApiImplicitParam(name = "bankName",value = "银行名称",required = false),
            @ApiImplicitParam(name = "state",value = "提现状态",required = false)
    })
     public void withdrawlog(Long id, String userPhone, String userName, String bankId, String bankName, String state, String from, String to
    ,HttpServletResponse response) throws IOException {
        Timestamp from1=null;
        Timestamp to1=null;
        if(from!=null&&!from.equals("")){
            from1=Timestamp.valueOf(from);
        }
        if(to!=null&&!to.equals("")){
            to1=Timestamp.valueOf(to);
        }
        //要导出的数据
        List<Outrecord> expMarkLogByPage = rechargerecordService.selectByWork1(id, userPhone, userName, bankId, bankName, state, from1, to1);
        System.out.println(expMarkLogByPage);
        System.out.println("2222222222222222222222222222222");
        // 工作簿对象
        HSSFWorkbook workbook = new HSSFWorkbook();
        // 创建工作表
        HSSFSheet sheet = workbook.createSheet("提现记录");
        String fileName = "提现记录导出记录"+".xls";
        // 将文件名中的中文部分被URL编码后的内容进行解析, 最终还是显示为中文状态
        fileName = URLEncoder.encode(fileName,"utf-8").replaceAll("\\+", "%20");
        // headers表示excel表中第一行的表头 在excel表中添加表头
        String[] headers = { "提现单号", "真实姓名", "用户手机号","用户类型","提现金额","提现手续费","到账金额","银行账号","银行名称","银行流水号","提交时间","审核人","审核时间","到帐时间","状态","提现记录备注","资金类型"};
        // 创建一个行对象, 作为表头
        HSSFRow row = sheet.createRow(0);
        for(int i=0;i<headers.length;i++){
            HSSFCell cell = row.createCell(i);   // 在行中添加单元格
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            cell.setCellValue(text);   // 把字段名添加到表头行上
        }
        //准备将时间格式处理为标准日期格式
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 添加数据行:
        int rowNum = 1;
        for (Outrecord item : expMarkLogByPage) {
            HSSFRow dataRow = sheet.createRow(rowNum);
            dataRow.createCell(0).setCellValue(item.getId());
            if (item.getUserName() == null) {
                dataRow.createCell(1).setCellValue("");
            } else {
                dataRow.createCell(1).setCellValue(item.getUserName());
            }
            if (item.getUserPhone() == null) {
                dataRow.createCell(2).setCellValue("");
            } else {
                dataRow.createCell(2).setCellValue(item.getUserPhone());
            }
            if (item.getUserType() == null) {
                dataRow.createCell(3).setCellValue("");
            } else {
                dataRow.createCell(3).setCellValue(item.getUserType());
            }
            if (item.getOutMoney() == null) {
                dataRow.createCell(4).setCellValue("");
            } else {
                dataRow.createCell(4).setCellValue(item.getOutMoney());
            }
            if (item.getOutCost() == null) {
                dataRow.createCell(5).setCellValue("");
            } else {
                dataRow.createCell(5).setCellValue(item.getOutCost());
            }
            if (item.getGetMoney() == null) {
                dataRow.createCell(6).setCellValue("");
            } else {
                dataRow.createCell(6).setCellValue(item.getGetMoney());
            }
            if (item.getBankId() == null) {
                dataRow.createCell(7).setCellValue("");
            } else {
                dataRow.createCell(7).setCellValue(item.getBankId());
            }
            if (item.getBankName() == null) {
                dataRow.createCell(8).setCellValue("");
            } else {
                dataRow.createCell(8).setCellValue(item.getBankName());
            }
            if (item.getBankSerial() == null) {
                dataRow.createCell(9).setCellValue("");
            } else {
                dataRow.createCell(9).setCellValue(item.getBankSerial());
            }
            if (item.getSubmitTime() == null) {
                dataRow.createCell(10).setCellValue("");
            } else {
                dataRow.createCell(10).setCellValue(dateFormat.format(item.getSubmitTime()));
            }
            if (item.getCheckMan() == null) {
                dataRow.createCell(11).setCellValue("");
            } else {
                dataRow.createCell(11).setCellValue(item.getCheckMan());
            }
            if (item.getCheckTime() == null) {
                dataRow.createCell(12).setCellValue("");
            } else {
                dataRow.createCell(12).setCellValue(dateFormat.format(item.getCheckTime()));
            }
            if (item.getGetTime() == null) {
                dataRow.createCell(13).setCellValue("");
            } else {
                dataRow.createCell(13).setCellValue(dateFormat.format(item.getGetTime()));
            }
            if (item.getState() == null) {
                dataRow.createCell(14).setCellValue("");
            } else {
                dataRow.createCell(14).setCellValue(item.getState());
            }
            if (item.getRemarks() == null) {
                dataRow.createCell(15).setCellValue("");
            } else {
                dataRow.createCell(15).setCellValue(item.getRemarks());
            }
            if (item.getMoneyType() == null) {
                dataRow.createCell(16).setCellValue("");
            } else {
                dataRow.createCell(16).setCellValue(item.getMoneyType());
            }
            rowNum++;
        }
        //返回给前端下载
        response.setContentType("application/octet-stream");
        //附件格式打卡，不是打开页面
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        response.flushBuffer();
        workbook.write(response.getOutputStream());

    }


}
